package com.ken.common.web.interception;

import com.ken.common.core.utils.AuthLocal;
import com.ken.common.core.utils.JsonUtils;
import com.ken.entity.auth.AuthUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Optional;

/**
 * 微服务端的用户授权拦截器
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class WebAuthInterception extends HandlerInterceptorAdapter {

    /**
     * 前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("[Auth-Parese] - 解析身份拦截器触发");
        //获得用户
        Optional
                .ofNullable(request.getHeader("auth_user"))
                .map(s -> {
                    try {
                        String decode = URLDecoder.decode(s, "utf-8");
                        AuthUser authUser = JsonUtils.json2Obj(decode, AuthUser.class);
                        log.debug("[Auth-Parese] - 成功解析出认证身份信息 - {}", authUser);
                        return authUser;
                    } catch (Exception e) {
                        log.error("[Auth-Parese] - 解析认证身份失败", e);
                    }
                    return null;
                })
                .ifPresent(authUser -> {
                    AuthLocal.setUser(authUser);
                });

        return super.preHandle(request, response, handler);
    }
}
